#!/bin/sh
#此脚本用于阻止国外访问本网站
mmode=$1
#下载全球IP地址分配情况，并过滤出中国网段,首次使用前，先执行下面这个命令
#wget -q -timeout=60 -O- 'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest' | awk --field-separator='|' '/CN|ipv4/ { printf("%s/%dn", $4, 32-log($5)/log(2)) }' > /root/china_ssr.txt

CNIP="/root/china_ssr.txt"

gen_iplist() {

cat <<-EOF

$(cat ${CNIP:=/dev/null} 2>/dev/null)

EOF

}

flush_r() {

iptables -F ALLCNRULE 2>/dev/null

iptables -D INPUT -p tcp -j ALLCNRULE 2>/dev/null

iptables -X ALLCNRULE 2>/dev/null

ipset -X allcn 2>/dev/null

}

mstart() {

ipset create allcn hash:net 2>/dev/null

#ipset -! -R <<-EOF

#$(gen_iplist | sed -e "s/^/add allcn /")

#EOF
#cat china_ssr.txt | awk '{ipset add allcn $0}'
# add china network routes
./ipset_add.sh
# allow https://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest
ipset add allcn 203.119.102.0/26
# allow docker lxr
ipset add allcn 172.17.0.0/16
# allow cci
ipset add allcn 10.247.0.0/16

# allow cloud service
ipset add allcn 100.125.0.0/16

# allow internal network in huaweicloud
ipset add allcn 192.168.0.0/16

#定义规则链 ALLCNRULE
iptables -N ALLCNRULE

#插入规则
iptables -I INPUT -p tcp -j ALLCNRULE

iptables -A ALLCNRULE -s 127.0.0.0/8 -j RETURN

iptables -A ALLCNRULE -s 169.254.0.0/16 -j RETURN

iptables -A ALLCNRULE -s 224.0.0.0/4 -j RETURN

iptables -A ALLCNRULE -s 255.255.255.255 -j RETURN

#可在此增加你的公网网段，避免调试ipset时出现自己无法访问的情况

iptables -A ALLCNRULE -m set --match-set allcn src -j RETURN

iptables -A ALLCNRULE -p tcp -j DROP

}

if [ "$mmode" == "stop" ] ;then

flush_r

exit 0

fi

flush_r

sleep 1

mstart
